<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\CommonEnum;
use app\enum\OceanEnum;
use app\enum\OeCodeEnum;
use app\model\CrontabTaskModel;
use app\model\OeAdvertiserDailyStatModel;
use app\service\BaseService;
use app\service\client\AccountService;
use app\service\CrontabTaskService;
use app\service\ocean\FinanceService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;

class OeAdvertiserDailyStatWork extends BaseWork implements DailyStatWork
{
    public string $tag;

    public array $clientAccountInfo = [];

    /**
     * 设置任务标识.
     * @param mixed $tag
     */
    public function setTag($tag = ''): bool
    {
        if (! is_null($tag)) {
            $this->tag = strval($tag);
        }
        return true;
    }

    /**
     * 获取任务标识.
     */
    public function getTag(): string
    {
        return $this->tag;
    }

    /**
     * 获取脚本名.
     */
    public function getCommandName(): string
    {
        return $this->getName();
    }

    /**
     * 获取定时任务.
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCrontabTaskInfo(): CrontabTaskModel
    {
        $where = [
            ['task_name', '=', $this->getName()],
            //            ['tag', '=', $this->getTag()],
        ];

        $obj = new CrontabTaskModel();
        $model = $obj->where($where)->field(true)->find();
        return $model instanceof CrontabTaskModel ? $model : $obj;
    }

    protected function configure()
    {
        // 指令配置
        $this->setName('oe_advertiser_daily_stat_work');
        $this->setDescription('巨量引擎-账户日流水拉取');
        $this->addArgument('type', Argument::REQUIRED, '类型  1：昨日报表 2：自定义时间');
        $this->addArgument('start_date', Argument::OPTIONAL, '开始日期');
        $this->addArgument('end_date', Argument::OPTIONAL, '结束日期');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        $output->writeln('=======巨量引擎-账户日流水拉取开始' . date('Y-m-d H:i:s', time()) . '=======');
        $type = $input->getArgument('type');
        $startDate = $input->getArgument('start_date');
        $endDate = $input->getArgument('end_date');

        if ($type == OceanEnum::YESTERDAY) {
            $yesterDay = date('Y-m-d', strtotime('-1 day'));
            $startDate = $yesterDay;
            $endDate = $yesterDay;
        } elseif ($type == OceanEnum::CUSTOM_DAY) {
            if (! $startDate || ! $endDate) {
                $output->writeln('===========开始时间，结束时间都必须存在！===========');
                return;
            }

            if ($startDate > $endDate) {
                $output->writeln('===========开始时间必须小于结束时间！===========');
                return;
            }
        }
        $redis = Cache::store('redis')->handler();
        $redisKey = (new RefreshYesterdayFundListWork())->getListKey(CommonEnum::OE_MEDIA);
        $st = time() + 5 * 60;
        // for ($i = 0; $i < 100; ++$i) {
        while (time() < $st) {
            $account = $redis->lPop($redisKey);
            if ($account) {
                $account = explode('_', $account);
                $advertiserId = $account[0];
                $execNum = intval($account[1]);
                //  获取账户信息
                $this->clientAccountInfo = BaseService::getClientAccountInfo($advertiserId);
                $page = 0;
                while (true) {
                    $token = AccountService::getToken(CommonEnum::OE_MEDIA, $advertiserId);
                    if (! $token) {
                        CrontabTaskService::fallPushList($redis, $redisKey, $advertiserId, $execNum, 'token获取失败');
                        break;
                    }
                    ++$page;
                    $result = $this->_getServiceAdvertiserDailyFlow($token, $advertiserId, $startDate, $endDate, $page);
                    if (! $result) {
                        $err = ['params' => ['token' => $token, 'advertiserId' => $advertiserId, 'startDate' => $startDate, 'endDate' => $endDate, 'page' => $page], 'response' => FinanceService::getError(0)];
                        $output->writeln('=======error:' . json_encode($err, JSON_UNESCAPED_UNICODE) . '=======');
                        CrontabTaskService::fallPushList($redis, $redisKey, $advertiserId, $execNum, json_encode($err, JSON_UNESCAPED_UNICODE));
                        break;
                    }
                    if (isset($result['code']) && $result['code'] != OeCodeEnum::SUCCESS) {
                        $err = ['params' => ['token' => $token, 'advertiserId' => $advertiserId, 'startDate' => $startDate, 'endDate' => $endDate, 'page' => $page], 'response' => $result];
                        $output->writeln('=======error:' . json_encode($err, JSON_UNESCAPED_UNICODE) . '=======');
                        CrontabTaskService::fallPushList($redis, $redisKey, $advertiserId, $execNum, json_encode($err, JSON_UNESCAPED_UNICODE));
                        break;
                    }

                    $list = $result['data']['list'];
                    if (count($list) == 0) {
                        break;
                    }

                    foreach ($list as $v) {
                        $statDate = intval(date('Ymd', strtotime($v['date'])));
                        $statInfo = $this->_getStatInfo($advertiserId, $statDate);
                        if (! empty($statInfo)) {
                            if (! $this->_isStatDataUpdate($statInfo, $v)) {
                                $result = $this->_updateStatData($statInfo['id'], $v);
                            }
                        } else {
                            $result = $this->_insertStatData($advertiserId, $v);
                        }

                        /*if (! $result) {
                            return self::getError(0);
                        }*/
                    }
                }
            } else {
                try {
                    CrontabTaskService::setSingleTask($this);
                } catch (\Exception $e) {
                    $output->writeln($e->getMessage());
                }
            }
        }

        $output->writeln('=======巨量引擎-账户日流水拉取结束' . date('Y-m-d H:i:s', time()) . '=======');
        $output->writeln('success');
    }

    /**
     * 获取获取广告账户流水信息.
     * @param string $token token
     * @param string $advertiserId 账户ID
     * @param string $startDate 开始时间
     * @param string $endDate 结束 时间
     * @return bool|mixed|string
     */
    protected function _getServiceAdvertiserDailyFlow(string $token = '', string $advertiserId = '', string $startDate = '', string $endDate = '', int $page = 1)
    {
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];

        $params = [
            'advertiser_id' => $advertiserId,
            'start_date' => $startDate,
            'end_date' => $endDate,
            'page' => $page,
            'page_size' => OceanEnum::MAX_PAGE_SIZE,
        ];

        return FinanceService::getAdvertiserDailyFlow($headers, $params);
    }

    /**
     * 判断是否需要更新.
     * @param array $oldData 旧数据
     * @param array $newData 新数据
     */
    private function _isStatDataUpdate(array $oldData = [], array $newData = []): bool
    {
        $one = $oldData['cost'] == $newData['cost'];
        $two = $oldData['reward_cost'] == $newData['reward_cost'];
        $three = $oldData['balance'] == $newData['balance'];
        $four = $oldData['income'] == $newData['income'];

        if ($one && $two && $three && $four) {
            return true;
        }

        return false;
    }

    /**
     * 获取广告账户流水信息.
     * @param string $advertiserId 账户ID
     * @param int $statDate 日期
     * @throws
     */
    private function _getStatInfo(string $advertiserId = '', int $statDate = 0): array
    {
        $where = [
            ['advertiser_id', '=', $advertiserId],
            ['stat_date', '=', $statDate],
        ];
        $info = (new OeAdvertiserDailyStatModel())->where($where)->field(true)->find();

        if (! $info) {
            return [];
        }

        return $info->toArray();
    }

    /**
     * 修改广告账户流水信息.
     * @param int $id 主键ID
     * @param array $params 参数
     */
    private function _updateStatData(int $id, array $params = [])
    {
        try {
            $data = [
                'balance' => $params['balance'], // 日终结余(单位：元)
                'cash_cost' => $params['cash_cost'], // 日终结余(单位元）
                'cost' => $params['cost'], // 总支出(单位元)
                'frozen' => $params['frozen'], // 冻结(单位元)
                'income' => $params['income'], // 总存入(单位元)
                'reward_cost' => $params['reward_cost'], // 赠款支出(单位元)
                'shared_wallet_cost' => $params['shared_wallet_cost'], // 共享钱包支出（单位元）
                'transfer_in' => $params['transfer_in'], // 总转入(单位元)
                'transfer_out' => $params['transfer_out'], // 总转出(单位元)
                'update_time' => time(),
            ];

            return (new OeAdvertiserDailyStatModel())->where('id', $id)->update($data);
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 插入广告账户流水信息.
     * @param string $advertiserId 账户ID
     * @param array $params 参数
     */
    private function _insertStatData(string $advertiserId = '', array $params = [])
    {
        try {
            $data = [
                'advertiser_id' => $advertiserId, // 账户ID
                'stat_date' => date('Ymd', strtotime($params['date'])), // 时间
                'balance' => $params['balance'], // 日终结余(单位：元)
                'cash_cost' => $params['cash_cost'], // 日终结余(单位元）
                'cost' => $params['cost'], // 总支出(单位元)
                'frozen' => $params['frozen'], // 冻结(单位元)
                'income' => $params['income'], // 总存入(单位元)
                'reward_cost' => $params['reward_cost'], // 赠款支出(单位元)
                'shared_wallet_cost' => $params['shared_wallet_cost'], // 共享钱包支出（单位元）
                'transfer_in' => $params['transfer_in'], // 总转入(单位元)
                'transfer_out' => $params['transfer_out'], // 总转出(单位元)
                'create_time' => time(),
                'project_id' => $this->clientAccountInfo['project_id'],
                'staff_id' => $this->clientAccountInfo['staff_id'],
            ];

            return (new OeAdvertiserDailyStatModel())->insert($data);
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }
}
